package com.ipoint.icompany.service;

import java.util.Calendar;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.Transactional;

import com.ipoint.icompany.model.Day;

@Name("dayGeneratorService")
@Scope(ScopeType.APPLICATION)
@Startup
public class DayGeneratorService {

	@In
	private EntityManager entityManager;

	public void generateDaysForYear(Integer year) {
		for (Day day : (new DayGenerator(year)).generateDaysForYear()) {
			try {
				entityManager.createQuery("from Day d where d.date = :date")
						.setParameter("date", day.getDate()).getSingleResult();
			} catch (NoResultException e) {
				entityManager.persist(day);
				entityManager.flush();
			}
		}
	}

	@Create
	@Transactional
	public void generateDaysForCurrentYear() {
		generateDaysForYear(Calendar.getInstance().get(Calendar.YEAR));
	}

}
